package cdu.zzq.controller;

import cdu.zzq.model.User;
import cdu.zzq.service.UserService;
import cdu.zzq.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import javax.servlet.RequestDispatcher;

@WebServlet("/mod_user")
public class ModifyUserServlet extends HttpServlet {

    UserService userService = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse
            response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        User user = new User();
        user.setId(Integer.parseInt(request.getParameter("id")));
        user.setName(request.getParameter("username"));
        user.setPassword(request.getParameter("password"));
        user.setSex(request.getParameter("sex"));
        String[]hobby=request.getParameterValues("hobby");
        String hobbies="";
        StringBuilder stringBuilder=new StringBuilder();
        if (hobby!=null){
            for (String s:hobby){
                stringBuilder.append(s+",");
            }
        }
        if (stringBuilder.length()>0){
            hobbies=stringBuilder.substring(0,stringBuilder.length()-1);
        }
        user.setHobby(hobbies);

        if(userService.mod(user)) {
            response.sendRedirect("userlist");
        } else {
            request.setAttribute("user", user);
            request.getRequestDispatcher("mod_user.do").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse
            response) throws ServletException, IOException {
        User user = userService.get(request.getParameter("id"));
        request.setAttribute("user", user);

        RequestDispatcher rd = request.getRequestDispatcher("mod_user.do");
        rd.forward(request, response);
    }
}
